

package com.taobao.diamond.server.service;
import com.taobao.diamond.server.utils.LdapPersonInfo;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

public class UserDaoLdapImpl {
    private LdapTemplate ldapTemplate;
    @Resource
    LdapContextSource ldapContextSource;

    public UserDaoLdapImpl() {
    }

    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    public List<String> getAllPersonNames(int scope, boolean distinct) {

       final ArrayList<String> allPersonCnList = new ArrayList();

        this.ldapTemplate.search("", "(objectclass=person)", this.createSearchControls(scope), new AttributesMapper()
        {
            public Object mapFromAttributes(Attributes attrs)
                    throws NamingException
            {
                Attribute attr = attrs.get("cn");

                if (attr == null) {
                    return null;
                }

                Enumeration ent = attr.getAll();
                while (ent.hasMoreElements()) {
                    allPersonCnList.add(ent.nextElement().toString());
                }

                return null;
            }
        });
        if(distinct) {
            ArrayList<String> templist = new ArrayList();
            Iterator i$ = allPersonCnList.iterator();

            while(i$.hasNext()) {
                String cn = (String)i$.next();
                if(!templist.contains(cn)) {
                    templist.add(cn);
                }
            }

            return templist;
        } else {
            return allPersonCnList;
        }
    }

    public List getAllPersons(int scope) {
        return this.ldapTemplate.search("", "(objectclass=person)", this.createSearchControls(scope), new LdapObjectAttributesMapper());
    }

    public List getPersonByUid(String uid, int scope) {
        return this.ldapTemplate.search("", "(&(objectclass=person)(uid=" + uid + "))", this.createSearchControls(scope), new LdapObjectAttributesMapper());
    }

    public List getPersonByCn(String cn, int scope) {
        return this.ldapTemplate.search("", "(&(objectclass=person)(cn=" + cn + "))", this.createSearchControls(scope), new LdapObjectAttributesMapper());
    }

    private SearchControls createSearchControls(int scope) {
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scope);
        return constraints;
    }

    public List getPersonByPersonEnty(LdapPersonInfo ldapPersonInfo, int scope) {
        StringBuffer strb = new StringBuffer("(&(objectclass=person)");
        if(ldapPersonInfo.getUid() != null && ldapPersonInfo.getUid() != "") {
            strb.append("(uid=" + ldapPersonInfo.getUid() + ")");
        }

        if(ldapPersonInfo.getFirstName() != null && ldapPersonInfo.getFirstName() != "") {
            strb.append("(givenname=" + ldapPersonInfo.getFirstName() + ")");
        }

        if(ldapPersonInfo.getLastName() != null && ldapPersonInfo.getLastName() != "") {
            strb.append("(sn=" + ldapPersonInfo.getLastName() + ")");
        }

        if(ldapPersonInfo.getCn() != null && ldapPersonInfo.getCn().size() > 0) {
            for(int i = 0; i < ldapPersonInfo.getCn().size(); ++i) {
                strb.append("(cn=" + ldapPersonInfo.getCn().get(i) + ")");
            }
        }

        if(ldapPersonInfo.getTelephone() != null && ldapPersonInfo.getTelephone() != "") {
            strb.append("(telephonenumber=" + ldapPersonInfo.getTelephone() + ")");
        }

        if(ldapPersonInfo.getFax() != null && ldapPersonInfo.getFax() != "") {
            strb.append("(facsimiletelephonenumber=" + ldapPersonInfo.getFax() + ")");
        }

        if(ldapPersonInfo.getMail() != null && ldapPersonInfo.getMail() != "") {
            strb.append("(mail=" + ldapPersonInfo.getMail() + ")");
        }

        String filter = strb.append(")").toString();
        return this.ldapTemplate.search("", filter, this.createSearchControls(scope), new LdapObjectAttributesMapper());
    }

    public LdapPersonInfo getLdapObjectByDn(String dn) {
        return (LdapPersonInfo)this.ldapTemplate.lookup(dn, new LdapObjectAttributesMapper()    );
    }

    private boolean loginCheack(String userDn, String password)
    {
        DirContext ctxs = this.ldapContextSource.getReadOnlyContext();
        try
        {
            Hashtable ht = new Hashtable();

            ht = ctxs.getEnvironment();

            ht.put("java.naming.security.principal", userDn);

            ht.put("java.naming.security.credentials", password);

            ht.put("java.naming.security.authentication", "simple");

            InitialDirContext initialDirContext = new InitialDirContext(ht);
            initialDirContext.close();
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();

            System.out.println("login false");

        } finally {
            try {
                ctxs.close();
            }
            catch (Exception ie)
            {
                ie.printStackTrace();
            }
        }

        return false;
    }

    public boolean userLogin(String uid, String password) {
        List dnlist = this.getUserDnByUid(uid);
        Iterator i$ = dnlist.iterator();

        Object dn;
        do {
            if(!i$.hasNext()) {
                return false;
            }

            dn = i$.next();
        } while(!this.loginCheack(dn.toString(), password));

        return true;
    }

    public List<String> getUserDnByUid(String uid) {
        DirContext ctx = this.ldapContextSource.getReadOnlyContext();
        ArrayList dn = new ArrayList();

        try {
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(2);
            NamingEnumeration en = ctx.search("", "uid=" + uid, constraints);

            while(en != null && en.hasMoreElements()) {
                Object obj = en.nextElement();
                if(obj instanceof SearchResult) {
                    SearchResult si = (SearchResult)obj;
                    dn.add(si.getNameInNamespace());
                }
            }

            ctx.close();
        } catch (Exception var9) {
            var9.printStackTrace();

            try {
                ctx.close();
            } catch (Exception var8) {
                var8.printStackTrace();
            }
        }

        return dn;
    }

    private void dispPerson(LdapPersonInfo temp) {
        System.out.println("-----------------------------");
        System.out.println("User(uid: " + temp.getUid() + ") listing...");
        System.out.println("First Name: " + temp.getFirstName());
        System.out.println("Last Name: " + temp.getLastName());
        System.out.println("Common Name: " + temp.getCn());
        System.out.println("User ID: " + temp.getUid());
        System.out.println("E-Mail: " + temp.getMail());
        System.out.println("Phone: " + temp.getTelephone());
        System.out.println("Fax: " + temp.getFax());
        System.out.println("List completed.");
        System.out.println("-----------------------------n");
    }

    public static void main(String[] str) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDaoLdapImpl test = (UserDaoLdapImpl)context.getBean("userDao");
        LdapContextSource ldapContextSource = (LdapContextSource)context.getBean("ldapContextSource");
        List list = test.getAllPersons(2);
        System.out.println(list);
    }

    private class LdapObjectAttributesMapper
            implements AttributesMapper
    {
        private LdapObjectAttributesMapper()
        {
        }

        public Object mapFromAttributes(Attributes attrs)
                throws NamingException
        {
            LdapPersonInfo LdapObject = new LdapPersonInfo();
            try
            {
                LdapObject.setUid(getAttribute(attrs, "uid"));

                LdapObject.setFirstName(getAttribute(attrs, "givenname"));

                LdapObject.setLastName(getAttribute(attrs, "sn"));

                LdapObject.setCn(getMoreSameAttributes(attrs, "cn"));

                LdapObject.setTelephone(getAttribute(attrs, "telephonenumber"));

                LdapObject.setFax(getAttribute(attrs, "facsimiletelephonenumber"));

                LdapObject.setMail(getAttribute(attrs, "mail"));
            } catch (NamingException n) {
                n.printStackTrace();
            }

            return LdapObject;
        }

        private String getAttribute(Attributes attrs, String attrName)
                throws NamingException
        {
            Attribute attr = attrs.get(attrName);

            if (attr == null) {
                return "";
            }
            return (String)attr.get();
        }

        private List<String> getMoreSameAttributes(Attributes attrs, String attrName)
                throws NamingException
        {
            Attribute attr = attrs.get(attrName);
            List elelist = new ArrayList();

            if (attr == null) {
                return null;
            }

            Enumeration ent = attr.getAll();
            while (ent.hasMoreElements())
                elelist.add(ent.nextElement().toString());
            return elelist;
        }
    }
}
